{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这部分内容主要参考http://docs.python-requests.org文档进行编写，可以通过jupyter运行内容，源文件放在https://github.com/Danielyan86/Python-Study/tree/master/AutomationTest/API/python_request"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 发起get请求 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "r = requests.get('https://api.github.com/')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 打印URL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.url"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 返回内容\n",
    "### 打印返回内容，requests会根据服务器返回自动解码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 当发起一个request请求时候，requests会根据http返回头部猜测编码格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.encoding"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### encoding的编码格式也可以被改变，当你改变r.encoding值时候，r.text内容也会做出相应的改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.encoding = 'ISO-8859-1'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 按照二进制格式输出 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.content"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 如果需要根据返回二进制内容创建图片，可以参考以下代码格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "from io import BytesIO\n",
    "i = Image.open(BytesIO(r.content))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 按照json格式输出\n",
    "为了防止json解码失败，r.json()会抛出异常，比如，如果返回204（没有内容），则r.json()抛出异常"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r = requests.get('https://api.github.com/events')\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 按照原生内容输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "requests.get('https://api.github.com/events', stream=True)\n",
    "r.raw"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "r.raw.read(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 可以根据下面这样的模式把streamed格式内容存入文件中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(filename, 'wb') as fd:\n",
    "    for chunk in r.iter_content(chunk_size=128):\n",
    "        fd.write(chunk)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "使用r.iter_content 可以帮你节省很多事情，chunk_size的值你可以根据实际使用场景而定"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## POST请求"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### post提交数据格式是字典，参数名是data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "payload = {'key1': 'value1', 'key2': 'value2'}\n",
    "\n",
    "r = requests.post(\"https://httpbin.org/post\", data=payload)\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当提交的表单一个key有多个value时候，可以用以下格式构建需要提交的字典参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "payload_dict = {'key1': ['value1', 'value2']}\n",
    "r2 = requests.post('https://httpbin.org/post', data=payload_dict)\n",
    "print(r2.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### json格式提交数据\n",
    "data参数可以接受按照json格式编码后的字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "url = 'https://httpbin.org/post'\n",
    "payload = {'some': 'data'}\n",
    "\n",
    "r = requests.post(url, data=json.dumps(payload))\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典格式的数据也可以直接传给json参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "url = 'https://httpbin.org/post'\n",
    "payload = {'some': 'data'}\n",
    "\n",
    "r = requests.post(url, json=payload)\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "需要注意的是，如果data或者files参数被赋值了，json参数会被忽略。使用json参数时候，需要把header里面的content-type更新为application/json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 提交文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = 'https://httpbin.org/post'\n",
    "files = {'file': open('your_test_file', 'rb')}\n",
    "r = requests.post(url, files=files)\n",
    "r.text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 也可以设置filename, content_type， headers:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = 'https://httpbin.org/post'\n",
    "files = {'file': ('report.xls', open('your_test_file', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}\n",
    "\n",
    "r = requests.post(url, files=files)\n",
    "r.text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 可以把string当成文件提交"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = 'https://httpbin.org/post'\n",
    "files = {'file': ('report.csv', 'some,data,to,send\\nanother,row,to,send\\n')}\n",
    "\n",
    "r = requests.post(url, files=files)\n",
    "r.json()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
